import React, { Ref, useCallback, useEffect, useRef, useState } from 'react';
import { Steps, Button, message, Spin } from 'antd';

import { OneModal } from '@/components/one-ui';

import { positionAPI } from '../../type';
import cls from 'classnames';

import '../../styles.less';

import { FirstStep } from './FirstStep';
import { OtherStepRoule } from './OtherStepRoule';
import MyIcon from '@/components/MyIcon';
import { useRequest } from 'umi';
import { addPosRequest, rouleDutySubjectRequest, useViewInfoPosData } from '../../hooks/usePositionOperation';
import { getPosIDs, getUserDepID, getUserID } from '@/utils';

export const UpdatePosModal: React.FC<positionAPI.IUpdateModal> = ({
  onClose,
  visible,
  dataSource, //用来渲染上级岗位值
  treeData, //测试数据
  intoModalType, //  add = 新增  |  edit = 编辑  |  grant = 角色  |  setDutyScope = 职权  |  setSubject = 科目
  cliResRows, //点击行数据
  onTableReload,
  deptCheckRows, //左侧选择的 部门数据
}) => {
  const steps = [
    {
      title: '基本信息',
    },
    {
      title: '授权角色',
    },
    {
      title: '设置管辖',
    },
    {
      title: '设置科目',
    },
  ];

  const prefix = 'update-drawer';
  const prefixModal = 'update-modal';

  const firstRef = useRef<positionAPI.IStepRef>(null); //第一步的 ref
  const otherStepRef = useRef<positionAPI.IStepRef>(null); //其他步骤 ref
  const posAddModalRef: Ref<positionAPI.IAddModalRef> = useRef(null); //弹框的ref

  const { detailInfoData, infoLoading } = useViewInfoPosData(cliResRows); //获取详情信息

  const [current, setCurrent] = useState(0); //保存 步数 标识
  const [recordPosForm, setRecordPosForm] = useState<any>(); //保存第一步填写的数据
  const recordForm = useCallback(
    (record: any) => {
      setRecordPosForm(record);
    },
    [recordPosForm],
  );

  const [secondRouleID, setSecondRouleID] = useState<any[]>([]); //保存第二步选择的key
  const [secondRouleRows, setSecondRouleRows] = useState<any[]>([]); //保存第二步选择的Row
  const saveSecondList = useCallback(
    (listID: any[], listRows?: any) => {
      setSecondRouleID(listID);
      setSecondRouleRows(listRows);
    },
    [secondRouleID, secondRouleRows],
  );

  const [thirdPowerID, setThirdPowerID] = useState<any[]>([]); //保存 第三步选择管辖的key
  const [thirdPowerRows, setThirdPowerRows] = useState<any[]>([]); //保存 第三步选择管辖的Row
  const saveThirdList = useCallback(
    (listID: any[], listRows?: any) => {
      setThirdPowerID(listID);
      setThirdPowerRows(listRows);
    },
    [thirdPowerID, thirdPowerRows],
  );

  const [fourthSubjectID, setFourthSubjectID] = useState<any[]>([]); //保存 第四步选择科目的key
  const [fourthSubjectRows, setFourthSubjectRows] = useState<any[]>([]); //保存 第四步选择科目的Row
  const saveFourthList = useCallback(
    (listID: any[], listRows?: any) => {
      setFourthSubjectID(listID);
      setFourthSubjectRows(listRows);
    },
    [fourthSubjectID, fourthSubjectRows],
  );

  useEffect(() => {
    //初始化 , 新增什么都不用管, 编辑需要调用详情获取初始化数据
    if (intoModalType == 'grant') {
      setCurrent(1);
    } else if (intoModalType == 'setDutyScope') {
      setCurrent(2);
    } else if (intoModalType == 'setSubject') {
      setCurrent(3);
    }
    if (detailInfoData && detailInfoData?.id) {
      let secDefaID = detailInfoData?.roleIds ? detailInfoData?.roleIds?.split(',') : [];
      saveSecondList(secDefaID);
      let thirdID = detailInfoData?.dutyScope ? detailInfoData?.dutyScope?.split(',') : [];
      saveThirdList(thirdID);
      let fourID = detailInfoData?.msubjectList?.length > 0 ? handForuIDS(detailInfoData?.msubjectList) : [];
      saveFourthList(fourID);
    }
  }, [intoModalType, detailInfoData]);

  // 获取第四步 详情选中id 处理
  const handForuIDS = (list: any) => {
    let ids: any = [];
    if (list?.length > 0) {
      list?.forEach((item: any) => {
        if (item?.subjectNum) {
          ids?.push(item.subjectNum);
        }
      });
    }
    if (ids?.length > 0) {
      return ids;
    } else {
      return '';
    }
  };

  // 上一步
  const onPrev = useCallback(() => {
    const prev = current - 1;
    if (current <= 0) {
      return;
    }
    setCurrent(prev);
  }, [current]);

  // 下一步
  const onNext = useCallback(() => {
    const next = current + 1;
    if (next >= 4) {
      return;
    }
    setCurrent(next);
  }, [current]);

  /* 关闭弹窗 */
  // const onCloseModal = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
  const onCloseModal = () => {
    if (posAddModalRef) {
      if (posAddModalRef.current) {
        if (posAddModalRef.current.onModalCancel) {
          posAddModalRef.current.onModalCancel();
        }
      }
    }
  };

  // 点击下一步的时候保存数据信息
  const isNextSaveData = useCallback(() => {
    if (current == 0) {
      //第一步 保存基本信息
      firstRef?.current?.form?.validateFields()?.then((values: any) => {
        recordForm(values);
        onNext();
      });
    } else if (current == 1) {
      //第二步, 保存角色信息
      let secondID = otherStepRef?.current?.leftCheckKeys;
      let secondRow = otherStepRef?.current?.rightRouleList;
      saveSecondList(secondID, secondRow);
      onNext();
    } else if (current == 2) {
      //第三步  保存管辖信息
      let thirdID = otherStepRef?.current?.leftCheckKeys;
      let thirdRow = otherStepRef?.current?.rightRouleList;
      saveThirdList(thirdID, thirdRow);
      onNext();
    }
  }, [current]);

  // 点击上一步保存数据信息
  const isPrevSaveData = useCallback(() => {
    if (current == 1) {
      //第二步, 保存角色信息
      let secondID = otherStepRef?.current?.leftCheckKeys;
      let secondRow = otherStepRef?.current?.rightRouleList;
      saveSecondList(secondID, secondRow);
      onPrev();
    } else if (current == 2) {
      //第三步  保存管辖信息
      let thirdID = otherStepRef?.current?.leftCheckKeys;
      let thirdRow = otherStepRef?.current?.rightRouleList;
      saveThirdList(thirdID, thirdRow);
      onPrev();
    } else if (current == 3) {
      //第四步 , 保存 科目信息
      let fourthID = otherStepRef?.current?.leftCheckKeys;
      let fourthRow = otherStepRef?.current?.rightRouleList;
      saveFourthList(fourthID, fourthRow);
      onPrev();
    }
  }, [current]);

  // 处理选择的科目数据
  const handleSubData = (subList: any[]) => {
    let subData: any[] = [];
    subList?.forEach((item: any) => {
      let subjectType = item?.subjectNum ? item?.subjectNum?.substring(0, 8) : item?.substring(0, 8);
      let subjectNum = item?.subjectNum ? item?.subjectNum : item;
      subData?.push({ subjectType, subjectNum });
    });
    if (subData?.length > 0) {
      return subData;
    } else {
      return null;
    }
  };

  // 保存新增编辑的岗位数据
  const savePosAddEditData = () => {
    // 第二步第三步需要传入 string 参数,
    let othIDs = otherStepRef?.current?.leftCheckKeys?.length > 0 ? otherStepRef?.current?.leftCheckKeys?.toString() : null;
    // 第四步需要传入object
    let msubIDS = otherStepRef?.current?.leftCheckKeys?.length > 0 ? otherStepRef?.current?.leftCheckKeys : null;

    if (intoModalType == 'add' || intoModalType == 'edit') {
      let payload = {
        ...recordPosForm,
        roleIds: current == 1 ? othIDs : secondRouleID?.length > 0 ? secondRouleID?.toString() : detailInfoData?.roleIds,
        roleFlag: current == 1 ? (othIDs ? true : false) : secondRouleID?.length > 0 ? true : false,

        dutyScope: current == 2 ? othIDs : thirdPowerID?.length > 0 ? thirdPowerID?.toString() : detailInfoData?.dutyScope,
        dutyFlag: current == 2 ? (othIDs ? true : false) : thirdPowerID?.length > 0 ? true : false,

        msubjectList:
          current == 3 ? handleSubData(msubIDS) : fourthSubjectID?.length > 0 ? handleSubData(fourthSubjectID) : handleSubData(detailInfoData?.msubjectList),
        subjectFlag: current == 3 ? (handleSubData(msubIDS) ? true : false) : fourthSubjectID?.length > 0 ? true : false,

        isOpen: 1,
        departmentID: deptCheckRows?.id,
        companyID: deptCheckRows?.companyID,
      };
      if (current == 0) {
        firstRef?.current?.form?.validateFields()?.then((values: any) => {
          addEditPosData?.run({ ...values, ...payload });
        });
      } else {
        addEditPosData?.run(payload);
      }

      // if (current == 0) {
      //   firstRef?.current?.form?.validateFields()?.then((values: any) => {
      //     let payload = {
      //       ...values,
      //       roleIds: secondRouleID?.length > 0 ? secondRouleID?.toString() : detailInfoData?.roleIds,
      //       roleFlag: secondRouleID?.length > 0 ? true : false,

      //       dutyScope: thirdPowerID?.length > 0 ? thirdPowerID?.toString() : detailInfoData?.dutyScope,
      //       dutyFlag: thirdPowerID?.length > 0 ? true : false,

      //       msubjectList: fourthSubjectID?.length > 0 ? handleSubData(fourthSubjectID) : handleSubData(detailInfoData?.msubjectList),
      //       subjectFlag: fourthSubjectID?.length > 0 ? true : false,

      //       isOpen: 1,
      //       departmentID: deptCheckRows?.id,
      //       companyID: deptCheckRows?.companyID,
      //     }
      //     addEditPosData?.run(payload)
      //   })
      // } else {
      //   let othIDs = otherStepRef?.current?.leftCheckKeys?.length > 0 ? otherStepRef?.current?.leftCheckKeys?.toString() : null
      //   let msubIDS = otherStepRef?.current?.leftCheckKeys?.length > 0 ? otherStepRef?.current?.leftCheckKeys : null
      //   let payload = {
      //     ...recordPosForm,
      //     roleIds: current == 1 ? othIDs : secondRouleID?.length > 0 ? secondRouleID?.toString() : detailInfoData?.roleIds,
      //     roleFlag: current == 1 ? othIDs ? true : false : secondRouleID?.length > 0 ? true : false,

      //     dutyScope: current == 2 ? othIDs : thirdPowerID?.length > 0 ? thirdPowerID?.toString() : detailInfoData?.dutyScope,
      //     dutyFlag: current == 2 ? othIDs ? true : false : thirdPowerID?.length > 0 ? true : false,

      //     msubjectList: current == 3 ? handleSubData(msubIDS) : fourthSubjectID?.length > 0 ? handleSubData(fourthSubjectID) : handleSubData(detailInfoData?.msubjectList),
      //     subjectFlag: current == 3 ? handleSubData(msubIDS) ? true : false : fourthSubjectID?.length > 0 ? true : false,

      //     isOpen: 1,
      //     departmentID: deptCheckRows?.id,
      //     companyID: deptCheckRows?.companyID,
      //   }
      //   addEditPosData?.run(payload)
      // }
    } else {
      let otherParams: any = {
        id: detailInfoData?.id,
        versionNum: detailInfoData?.versionNum,
        modifyDepartmentID: getUserDepID(),
        modifyPositionID: getPosIDs(),
        modifyerID: getUserID(),
        roleIds: current == 1 ? othIDs : secondRouleID?.length > 0 ? secondRouleID?.toString() : detailInfoData?.roleIds,
        dutyScope: current == 2 ? othIDs : thirdPowerID?.length > 0 ? thirdPowerID?.toString() : detailInfoData?.dutyScope,
        msubjectList:
          current == 3 ? handleSubData(msubIDS) : fourthSubjectID?.length > 0 ? handleSubData(fourthSubjectID) : handleSubData(detailInfoData?.msubjectList),
      };
      addEditPosData?.run(otherParams);
    }
  };

  // 新增 或者编辑 方法
  const addEditPosData = useRequest(
    (payload: any) => {
      if (intoModalType == 'add') {
        return addPosRequest(payload, 'add');
      } else if (intoModalType == 'edit') {
        let params: any = {
          seq: detailInfoData?.seq,
          name: detailInfoData?.name,
          ...payload,
          id: detailInfoData?.id,
          versionNum: detailInfoData?.versionNum,
          rank: detailInfoData?.rank,
          roleFlag: chaRouDutySub('roule', payload?.roleIds),
          dutyFlag: chaRouDutySub('dutySco', payload?.dutyScope),
          subjectFlag: chaRouDutySub('subject', payload?.msubjectList),
          modifyDepartmentID: getUserDepID(),
          modifyPositionID: getPosIDs(),
          modifyerID: getUserID(),
        };
        return addPosRequest(params, 'edit');
      } else if (intoModalType == 'grant') {
        let params: any = {
          ...payload,
          // positionIds: detailInfoData?.id,
          userIds: getUserID(),
        };
        delete params['dutyScope'];
        delete params['msubjectList'];
        return rouleDutySubjectRequest(params, intoModalType);
      } else if (intoModalType == 'setDutyScope') {
        let params: any = {
          ...payload,
        };
        delete params['roleIds'];
        delete params['msubjectList'];
        return rouleDutySubjectRequest(params, intoModalType);
      } else if (intoModalType == 'setSubject') {
        let params: any = {
          ...payload,
        };
        delete params['dutyScope'];
        delete params['roleIds'];
        return rouleDutySubjectRequest(params, intoModalType);
      }
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          onCloseModal();
          onTableReload();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // 判断 角色 管辖, 科目是否有变化
  const chaRouDutySub = (chanType: string, payList: any) => {
    let flag: boolean = false;
    let infoList: any = null;
    let checkIDList: any = chanType == 'subject' ? null : payList ? payList?.split(',') : null;
    if (chanType == 'roule') {
      infoList = detailInfoData?.roleIds ? detailInfoData?.roleIds?.split(',') : null;
    } else if (chanType == 'dutySco') {
      infoList = detailInfoData?.dutyScope ? detailInfoData?.dutyScope?.split(',') : null;
    } else if (chanType == 'subject') {
      checkIDList = aloneFourFlagList(payList);
      infoList = aloneFourFlagList(detailInfoData?.msubjectList);
    }

    // if (infoList?.length > -1 && checkIDList?.length > -1) {  //判断 是否 有, 详情里 角色 id 和选中的角色 id
    if (infoList?.length == checkIDList?.length) {
      //判断 详情和选中角色 id 是否相同
      infoList?.forEach((item: any) => {
        if (!checkIDList?.includes(item)) {
          flag = true;
        }
      });
    } else {
      //不相同返回true, 修改角色数据
      flag = true;
    }
    // } else {
    //   flag = false
    // }
    return flag;
  };

  // 单独处理科目选择的 id, 和详情的id
  const aloneFourFlagList = (aloneList: any) => {
    let alonIDS: any = [];
    if (aloneList && aloneList?.length > 0) {
      aloneList?.forEach((item: any) => {
        if (item?.subjectNum) {
          alonIDS?.push(item?.subjectNum);
        }
      });
    }
    return alonIDS;
  };

  // 处理返回的modal title
  const modalTitlePos = () => {
    switch (intoModalType) {
      case 'add':
        return '添加岗位';
      case 'edit':
        return '编辑岗位';
      case 'grant':
        return '授权角色';
      case 'setDutyScope':
        return '设置管辖';
      case 'setSubject':
        return '设置科目';
      default:
        return '';
    }
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={posAddModalRef}
      title={modalTitlePos()}
      width={document.body.clientWidth * 0.5}
      onCancel={onClose}
      className={cls(prefixModal)}
      footer={
        <>
          <div>
            {(intoModalType == 'edit' || intoModalType == 'add') && (
              <>
                {current != 0 && (
                  <Button
                    onClick={(event: any) => {
                      isPrevSaveData();
                    }}
                    type={'primary'}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                  >
                    上一步
                  </Button>
                )}
                {current != 3 && (
                  <Button
                    onClick={(event: any) => {
                      isNextSaveData();
                    }}
                    type={'primary'}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    disabled={intoModalType == 'add' ? false : infoLoading}
                  >
                    下一步
                  </Button>
                )}
              </>
            )}

            <Button onClick={onCloseModal}>取消</Button>
            <Button
              type={'primary'}
              onClick={savePosAddEditData}
              loading={addEditPosData?.loading}
              disabled={intoModalType == 'add' ? false : infoLoading}
              onMouseOut={(event: any) => {
                event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
              }}
            >
              保存
            </Button>
          </div>
        </>
      }
      bodyStyle={{
        padding: '5px 10px',
        // height: window.screen.height * 0.5,
      }}
      centered
    >
      <Spin spinning={intoModalType == 'add' ? false : infoLoading}>
        <div className={cls(prefix)}>
          {(intoModalType == 'edit' || intoModalType == 'add') && (
            <div className={cls(prefix + '-header')}>
              <Steps size="small" current={current} items={steps} />
            </div>
          )}
          <div className={cls(prefix + '-content')}>
            {current == 0 && <FirstStep pidPosList={dataSource} ref={firstRef} recordPosForm={recordPosForm} detailInfoData={detailInfoData} />}

            {/* 第二步设置角色 */}
            {current == 1 && (
              <OtherStepRoule
                ref={otherStepRef}
                otherStepType={'secondStep'}
                treeIcon={<MyIcon type="user" style={{ marginRight: 5 }} />}
                secondRouleID={secondRouleID}
                secondRouleRows={secondRouleRows}
                detailInfoData={detailInfoData}
              />
            )}

            {/* 第三步设置管辖 */}
            {current == 2 && (
              <OtherStepRoule
                ref={otherStepRef}
                otherStepType={'thirdStep'}
                treeIcon={<MyIcon type="zuzhijigou" style={{ marginRight: 5 }} />}
                thirdPowerID={thirdPowerID}
                thirdPowerRows={thirdPowerRows}
                thirdData={treeData}
                detailInfoData={detailInfoData}
              />
            )}

            {/* 第四步 设置科目 */}
            {current == 3 && (
              <OtherStepRoule
                ref={otherStepRef}
                otherStepType={'fourthStep'}
                treeIcon={<MyIcon type="shu" style={{ marginRight: 5 }} />}
                fourthSubjectID={fourthSubjectID}
                fourthSubjectRows={fourthSubjectRows}
                detailInfoData={detailInfoData}
              />
            )}
          </div>
        </div>
      </Spin>
    </OneModal>
  );
};
